package com.guozcc.bootweb.api.component;

import com.guozcc.bootweb.api.bean.User;
import com.guozcc.bootweb.api.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


//@CacheConfig(cacheNames="",keyGenerator="")
@Slf4j
@Component
public class ApiDemoComponent {
    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    public List<User> testTransactional(String  UserName) throws Exception{
        List<User> users = userMapper.getUserByUserName(UserName);
        if(users!=null&&users.size()!=0){
            User user = users.get(0);
            user.setUsername(user.getUsername()+"Transactional-1");
            userMapper.insertUser(user);
            user.setUsername(user.getUsername().replace("Transactional-1","Transactional-2"));
            userMapper.insertUser(user);
        }
        return users;
    }

    @Async("guozccThreadPoolTaskExecutor") // 声明异步方法
    public void testAsynTask() throws Exception{
        log.info("异步执行开始");
        Thread.sleep(10*1000);
        log.info("异步执行结束");
    }

    /**
     * SpringBoot缓存的使用
     * @Cacheable:先获取缓存，没有则调方法，再创建
     *      key不能用#result，没意义
     *      condition = "#userName eq '郭子超'"    只缓存    郭子超
     *      unless = "#result==null||#result.size()==0"   返回结果为空，不缓存
     */
    @Cacheable(cacheNames = {"getUserListByUserName"},key = "#userName",condition = "#userName eq '黄成一'" ,unless = "#result==null||#result.size()==0" )
    public List<User> getUserListByUserName(String  userName) throws Exception{
        List<User> users = userMapper.getUserByUserName(userName);

        return users;
    }

    /**
     * SpringBoot缓存的使用
     * @CachePut：先调方法，把结果放到缓存中
     *
     *
     *
     * 测试：
     *      getUserListByUserName  查到俩条，放到缓存
     *      updateUser  更新缓存成1条
     *      getUserListByUserName ，查询缓存返回1条，但数据库里有俩条，@CachePut生效
     */
    @CachePut(cacheNames = {"getUserListByUserName"},key = "#user.username")
    @Transactional(rollbackFor = Exception.class)
    public List<User> updateUser(User user) throws Exception{
        userMapper.updateUser(user);
        List<User> userlist = new ArrayList<User>();
        userlist.add(user);
        return userlist;
    }

    /**
     * SpringBoot缓存的使用
     * @CacheEvict 删除缓存
     *      allEntries = true  删除cacheNames下所有缓存
     *      beforeInvocation =true  是否在方法之前执行（默认方法之后执行，方法不报错，不执行）
     */
    @CacheEvict(cacheNames = {"getUserListByUserName"},key = "#user.username" )
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserById(User user) throws Exception{
        log.info("删除userid"+user.getUserid());
//        userMapper.updateUser(user);

    }


    /**
     * @Caching  组合缓存注解,定义复杂缓存规则
     */
    @Caching(
            cacheable = {
                    @Cacheable(cacheNames = {"getUserListByUserName"},key = "#userName",condition = "#userName eq '黄成一'" ,unless = "#result==null||#result.size()==0" )
            },
            put={
                    @CachePut(cacheNames = {"getUserListByUserName"},key = "#userName"),
                    @CachePut(cacheNames = {"getUserListByUserName"},key = "#userName")
            },
            evict={
                    @CacheEvict(cacheNames = {"getUserListByUserName"},key = "#userName" )
            }

    )
    public void demo(String userName){

    }
    /**
     *  @CacheConfig(cacheNames="user",keyGenerator="mykeyGenerator")  放到类上，抽取缓存的公共配置参数
     */



}
